import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:proj_sfv/component/LoadingOverlay.dart';
import 'package:proj_sfv/component/MyListItem.dart';
import 'package:proj_sfv/component/MyNotification.dart';
import 'package:proj_sfv/component/SimpleVideo.dart';
import 'package:proj_sfv/domain/UserInfo.dart';
import 'package:proj_sfv/http/api.dart';
import 'package:proj_sfv/http/requests.dart';
import 'package:proj_sfv/pages/UserVoListPage.dart';
import 'package:proj_sfv/store/MyArguments.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tencent_cloud_chat_uikit/business_logic/view_models/tui_friendship_view_model.dart';
import 'package:tencent_cloud_chat_uikit/data_services/services_locatar.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';

class MyPage extends StatefulWidget {

  const MyPage();

  @override
  State<MyPage> createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> with AutomaticKeepAliveClientMixin {
  Key _key = UniqueKey();
  int id;
  String token;
  var _login = false;
  var _loading = true;
  var _profileUrl = 'https://flutter.github.io/assets-for-api-docs/assets/widgets/owl.jpg';
  TUIFriendShipViewModel model = serviceLocator<TUIFriendShipViewModel>();

  void tryLogin () async {
    var data = await Navigator.pushNamed(context, "/user/login");
    if (data == "success") {
      print('login success!');
      initProfile();
    }
  }

  void initProfile() async {
    SharedPreferences.getInstance().then((value) async {
      token = value.getString("token");
      id = value.getInt("id");
      if (token != null && id != null) {
        var resp = await getBasicMyRequest(context, id, token);
        if (resp != null) {
          setState(() {
            Uri url = Uri.https(cosHost, resp.profile + ".jpg");
            _profileUrl = url.toString();
            _login = true;
            _loading = false;
          });
        }
      } else {
        setState(() {
          _profileUrl = "";
          _login = false;
          _loading = false;
        });
      }
    });
  }

  void tryGetInfos() {
    if (_login) {
      Navigator.pushNamed(context, "/user/info", arguments: MyArguments.ofUser(id, token));
      initState(); // 刷新状态防止token过期
    }
  }

  @override
  void initState() {
      // 请求头像
    initProfile();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return LoadingOverlay(
      isLoading: _loading,
      child: Column(
        key: _key,
        mainAxisAlignment: MainAxisAlignment.center,
        mainAxisSize: MainAxisSize.max,
        children: [
          SizedBox(
            height: 200,
            child: ColoredBox(
              color: Colors.black12,
              child: Stack(
                children: [
                  Center(
                    child: AspectRatio(
                      aspectRatio: 0.8,
                      child: InkWell(
                        onTap: tryGetProfile,
                        child: CircleAvatar(
                          backgroundImage: NetworkImage(_profileUrl, scale: 0.1),
                          radius: 100,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          Expanded(
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: ListView(
                  children: [
                    Visibility(
                      child:
                      MyListItem(
                          "登陆",
                          Icons.login,
                          tryLogin,
                          ""
                      ),
                      visible: !_login,
                    ),
                    Visibility(
                      visible: _login,
                      child: Column(
                        children: [
                          MyListItem(
                                "我的信息",
                                Icons.person,
                                tryGetInfos,
                              ""
                            ),
                          MyListItem(
                              "我的作品",
                              Icons.video_camera_back_outlined,
                              () {
                                Navigator.pushNamed(context, "/user/video", arguments: MyArguments.two(id, token, VideoPageType.MY));
                              }, ""),
                          MyListItem("我的点赞",
                              Icons.thumb_up,
                              () {
                                Navigator.pushNamed(context, "/user/video/like", arguments: MyArguments.two(id, token, VideoPageType.LIKE));
                              },
                              ""),
                          MyListItem("我的点踩", Icons.thumb_down, () {
                            Navigator.pushNamed(context, "/user/video/dislike", arguments: MyArguments.two(id, token, VideoPageType.DISLIKE));
                          }, ""),
                          MyListItem("我的收藏", Icons.collections, () {
                            Navigator.pushNamed(context, "/user/video/collect", arguments: MyArguments.two(id, token, VideoPageType.COLLECT));
                          }, ""),
                          MyListItem("我的关注", Icons.volunteer_activism_outlined, () {
                            Navigator.push(context, MaterialPageRoute(builder: (context) =>
                                UserVoListPage(token, id, "$getFollowed${id}", "我的关注列表", ""),
                            ));
                          }, ""),
                          MyListItem("我的粉丝", Icons.people_outline, () {
                            Navigator.push(context, MaterialPageRoute(builder: (context) =>
                                UserVoListPage(token, id, "$getFans${id}", "我的粉丝列表", ""),
                            ));
                          }, ""),
                        ],
                      ),
                    ),
                    Visibility(child: MyListItem("退出登陆", Icons.logout, tryLogout, "")
                    , visible: _login)
                  ],
                ),
              )
          )
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;

  void tryLogout() async {
    logoutRequest(context, id, token);
    SharedPreferences.getInstance().then((value) => {
      value.remove("token"),value.remove("id")
    });
    V2TimCallback logoutRes = await TencentImSDKPlugin.v2TIMManager.logout();
    V2TimCallback unInitSDKRes =
    await TencentImSDKPlugin.v2TIMManager.unInitSDK();
    if (unInitSDKRes.code == 0) {
      // 反初始化SDK成功的逻辑
    }
    if(logoutRes.code == 0){
      Fluttertoast.showToast(msg: "im登出成功！" , webShowClose: true);
    }
    model.loadData();
    Navigator.pushNamedAndRemoveUntil(context, "/home", (route) => route == null);
  }

  void tryGetProfile() async {
    var url = Navigator.pushNamed(context, "/user/profile", arguments: MyArguments.ofUser(id, token));
    setState(() {
      _loading = true;
    });
    Future.delayed(Duration(seconds: 4), initProfile);
  }
}